from flask import Blueprint, render_template, request, session, flash, redirect, url_for
from app.forms import LoginForm, RegisterForm
from app.models import User
from app import db

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if request.method == 'POST' and form.validate_on_submit():
        # 根据邮箱查找用户
        user = User.query.filter_by(email=form.email.data).first()
        # 验证密码
        if user and user.check_password(form.password.data):
            # 将用户ID存储到session中
            session['user_id'] = user.id
            session['username'] = user.username

            # print(f"设置session后: {session}")
            # print(f"session中的user_id: {session.get('user_id')}")
            # print(f"session中的username: {session.get('username')}")

            flash('登录成功！', 'success')
            return redirect(url_for('main.index'))
        else:
            flash('邮箱或密码错误！', 'danger')
    return render_template('auth/login.html', form=form)

@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    
    if form.validate_on_submit():
        # 检查邮箱是否已被注册
        existing_user = User.query.filter_by(email=form.email.data).first()
        if existing_user:
            flash('该邮箱已被注册，请使用其他邮箱', 'danger')
            return redirect(url_for('auth.register'))
        
        # 检查用户名是否已被注册
        existing_username = User.query.filter_by(username=form.username.data).first()
        if existing_username:
            flash('该用户名已被使用，请选择其他用户名', 'danger')
            return redirect(url_for('auth.register'))
        
        # 创建新用户
        new_user = User(
            username=form.username.data,
            email=form.email.data
        )
        
        # 设置密码哈希
        new_user.set_password(form.password.data)
        
        # 保存到数据库
        db.session.add(new_user)
        db.session.commit()
        
        # 登录新用户
        session['user_id'] = new_user.id
        session['username'] = new_user.username
        
        flash('注册成功！欢迎加入我们', 'success')
        return redirect(url_for('main.index'))
    
    return render_template('auth/register.html', form=form)

@auth_bp.route('/logout')
def logout():
    # 清除session
    session.clear()
    flash('已成功退出登录', 'success')
    return redirect(url_for('main.index'))